package com.sdksoft.readcard

import com.csht.enums.ReadCardType
import com.csht.enums.StatusCode
import com.csht.listener.InitListener
import com.sdksoft.readcard.databinding.PortSettingBinding

class PortActivity : BaseIDCardActivity(), InitListener {

    private var initSuccess = false

    private lateinit var portSettingBinding: PortSettingBinding

    private var readType = ""

    override fun initView() {
        super.initView()
        portSettingBinding = PortSettingBinding.inflate(layoutInflater)
        baseActivityBinding.llContent.addView(portSettingBinding.root, 0)
        setTitleText("串口读卡")
        readType = intent.getStringExtra("readType") ?: ""
        buildReadCardType()
        readCardManager.readCardInit(this)
        portSettingBinding.apply {
            save.setOnClickListener {
                if (initSuccess) {
                    readCardManager.readCardStop()
                    initSuccess = false
                }
                initRead()
            }
        }
    }

    private fun initRead(){
        portSettingBinding.apply {
            readSettingBuilder
                // 设置串口号、波特率（串口读卡时需要设置）
                .buildSerialPort(deviceFilePath.text.toString().trim(), baudrate.text.toString().trim().toInt())
            buildReadCardType()
        }
        readCardManager.readCardInit(this)
    }

    private fun buildReadCardType(){
        when (readType) {
            "1" -> {
                readSettingBuilder.buildReadCardType(ReadCardType.SERIALPORT)
            }
            "2" -> {
                readSettingBuilder.buildReadCardType(ReadCardType.SERIALPORT_DK)
            }
            else -> {
                readSettingBuilder.buildReadCardType(ReadCardType.SERIALPORT)
            }
        }
    }

    override fun onResponse(code: Int, msg: String) {
        mHandler.post {
            if (code == StatusCode.ININ_ING.code) {
                appendLog("初始化中$code，$msg")
            } else if (code != StatusCode.ININ_OK.code) {
                initSuccess = false
                appendLog("初始化失败$code")
            } else {
                initSuccess = true
                appendLog("初始化成功，开始读卡")
                mHandler.postDelayed({
                    baseActivityBinding.tvVersion.apply {
                        append("\n")
                        append("\n读卡板：${readCardManager.readFirmwareVersion()}")
                    }
                }, 1000)
                readCardManager.readCardStart(this)
            }
        }
    }
}